package com.yuexun.dhdoctor.module.personalPlan.ui;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.personalPlan.adapter.MyShareAdapter;
import com.yuexun.dhdoctor.module.personalPlan.bean.MyShareBean;
import com.yuexun.dhdoctor.module.personalPlan.bean.ShareBean;
import com.yuexun.dhdoctor.module.personalPlan.model.impl.MyShareModel;
import com.yuexun.dhdoctor.module.personalPlan.presenter.IMySharePresenter;
import com.yuexun.dhdoctor.module.personalPlan.presenter.impl.MySharePresenter;
import com.yuexun.dhdoctor.module.personalPlan.ui.view.IMyShareView;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshList;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/9/13.
 */
public class Act_MyShare extends BaseKJActivity implements IMyShareView {

    @Bind(R.id.myshare_list)
    PullToRefreshList myshareList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.myshare_count_tv)
    TextView myshareCountTv;
    @Bind(R.id.backTxt)
    TextView backTxt;

    private ListView mList;

    BaseAdapter adapter;
    ArrayList<MyShareBean.DatasEntity> datasEntities = new ArrayList<>();
    IMySharePresenter presenter;

    ArrayList<People> usersBeans_origin = new ArrayList<>();
    private String type;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_myshare);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        type = getIntent().getExtras().getString("type");
//        backTxt.setText(type);
        listViewPreference();
        presenter = new MySharePresenter(new MyShareModel(), this);
        ApiGetList();
    }

    private void ApiGetList() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        presenter.getMyShareList(params);
    }


    @OnClick({R.id.back, R.id.myshare_delete, R.id.myshare_add_member})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.myshare_delete:
                if (datasEntities.size() == 0) {
                    ViewInject.toast("无共享人员");
                    break;
                }
                Bundle bundle_delete = new Bundle();
                Intent intent_delete = new Intent(this, Act_MyShare_DeleteMember.class);
                bundle_delete.putSerializable("persons", datasEntities);
                intent_delete.putExtras(bundle_delete);
                aty.startActivityForResult(intent_delete, 2);
                break;
            case R.id.myshare_add_member:
                ArrayList<People> peoples = new ArrayList<>();
                for (MyShareBean.DatasEntity item : datasEntities) {
                    People people = new People();
                    people.setUserId(item.getSharerAccountId() + "");
                    people.setUserName(item.getOwnerName());
                    peoples.add(people);
                }

                Bundle bundle_add = new Bundle();
//                Intent intent_add = new Intent(this, Act_Choice_People.class);
                bundle_add.putSerializable("persons", peoples);
//                intent_add.putExtras(bundle_add);
//                aty.startActivityForResult(intent_add, 1);
                break;
        }
    }

    @Override
    public void showMyShareList(MyShareBean myShareBean) {
        datasEntities = myShareBean.getDatas();
        adapter = new MyShareAdapter(mList, datasEntities, R.layout.item_myshare);
        mList.setAdapter(adapter);
        emptyLayout.dismiss();
        myshareCountTv.setText("已共享给" + datasEntities.size() + "人");
    }

    private void listViewPreference() {
        mList = myshareList.getRefreshView();
        mList.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        mList.setOverscrollFooter(null);
        mList.setOverscrollHeader(null);
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        myshareList.setPullLoadEnabled(false);//设置上拉刷新功能关闭
        ((FooterLoadingLayout) myshareList.getFooterLoadingLayout())
                .setNoMoreDataText("已经是最新状态");

        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
            }
        });

        myshareList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                Map<String, String> params = new HashMap<>();
                params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                presenter.getMyShareList(params);
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                myshareList.setHasMoreData(false);
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                ApiGetList();
            }
        });
    }

    @Override
    public void PullDownRefreshState(int state) {
        switch (state) {
            case AppConfig.DOWNLOAD_SUCCESS:
                myshareList.onPullDownRefreshComplete();
                myshareList.onPullUpRefreshComplete();
                break;
            case AppConfig.DOWNLOAD_NETERROR:
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                break;
            case AppConfig.DOWNLOAD_NODATA:
                emptyLayout.setErrorType(EmptyLayout.NODATA);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                usersBeans_origin = (ArrayList<People>) data.getExtras().getSerializable("persons");
                ApiAddPeople();
                break;
            case 101:
                ApiGetList();
                break;
            default:
                break;
        }
    }

    //共享人员
    private void ApiAddPeople() {
        String receive_name = "";
        String receive_id = "";

        String url = AppConfig.WEB_SYSTEM + "sharePersonalSchedule.json?sessionUuid=" + PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID)
                + "&scopeFlag=1";

        for (int i = 0; i < usersBeans_origin.size(); i++) {
            receive_name += (usersBeans_origin.get(i).getUserName() + ";");
            receive_id += ("&receiverIds=" + usersBeans_origin.get(i).getUserId());
        }
        url += receive_id;

        HttpParams params = new HttpParams();
        params.put("receiverNames", receive_name);

        KJHttp kjHttp = new KJHttp();
        kjHttp.post(url, params, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                ShareBean shareBean = JSON.parseObject(t, ShareBean.class);
                if (shareBean.getStatus().equals("200")) {
                    setUi(true);
                } else {
                    setUi(false);
                }
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                ViewInject.toast(strMsg);
            }
        });
    }

    private void setUi(boolean is) {
        if (is) {
            datasEntities.clear();
            for (int i = 0; i < usersBeans_origin.size(); i++) {
                MyShareBean.DatasEntity datasEntity = new MyShareBean.DatasEntity();
                datasEntity.setSharerAccountId(Integer.valueOf(usersBeans_origin.get(i).getUserId()));
                datasEntity.setSharerName(usersBeans_origin.get(i).getUserName());
                datasEntities.add(datasEntity);
            }
            adapter = new MyShareAdapter(mList, datasEntities, R.layout.item_myshare);
            mList.setAdapter(adapter);
            myshareCountTv.setText("已共享给" + datasEntities.size() + "人");
        } else {
            ViewInject.toast("共享失败");
        }
    }

}
